'use strict';

const _ = require('lodash');
/**
 * Export
 */

 /**
  * @description pad the string object with
  * @param {string} padstr - pad characters
  * @param {string} str - source string object
  * @param {string} padLeft - set the pad side
  * @returns {string}
  */
 module.exports.pad = function(padstr, str, padLeft) {
  if (typeof str === 'undefined')
    return padstr;
  if (padLeft) {
    return (padstr + str).slice(-padstr.length);
  } else {
    return (str + padstr).substring(0, padstr.length);
  }
}

/**
 * @description get the value from enum
 * @param {object} EnumValues - candidate value map
 * @param {string} key - transfer type
 * @param {string} enumVal - predefined enum value
 * @param {string} candidate - candidate val
 * @returns {integer}
 */
 module.exports.Enum2Val = function(EnumValues, key, enumVal, candidate) {
  let iVal = 255;
  if (key in EnumValues) {
    let idx = _.indexOf(EnumValues[key].vals, enumVal);
    if (idx === -1) {
      idx = _.indexOf(EnumValues[key].vals, candidate);
    }
    if (idx !== -1) {
      iVal = idx + EnumValues[key].base;
    }
  }
  return iVal;
}

/**
 * @description get the enum from integer value
 * @param {object} EnumValues - candidate value map
 * @param {string} key - transfer type
 * @param {integer} iVal - predefined value
 * @returns {string}
 */
 module.exports.Val2Enum = function(EnumValues, key, iVal) {
  let strVal = "Unknown";
  if (_.isInteger(iVal)===true && iVal >= 0) {
    if (key in EnumValues) {
      let idx = iVal - EnumValues[key].base;
      if (idx >= 0 && idx < EnumValues[key].vals.length) {
        strVal = EnumValues[key].vals[idx];
      }
    }
  }
  return strVal;
}

/**
 * @description get the enum from hex value
 * @param {object} EnumBinVals - candidate bin enum map
 * @param {string} key - transfer type
 * @param {object} val - predefined value
 * @returns {string}
 */
module.exports.Bin2Enum = function(EnumBinVals, key, val) {
  let strVal = "Unknown";
  if (val === null) {
    return strVal;
  }

  let hexVal = val;
  if (val instanceof Buffer) {
    hexVal = val.toString('hex');
  }

  if (_.has(EnumBinVals, key)) {
    if (_.has(EnumBinVals[key], hexVal)) {
      strVal = EnumBinVals[key][hexVal];
    }
  }
  return strVal;
}

// examples:
// var t1Closure = template`${0}${1}${0}!`;
// t1Closure('Y', 'A');  // "YAY!" 
// var t2Closure = template`${0} ${'foo'}!`;
// t2Closure('Hello', {foo: 'World'});  // "Hello World!"
module.exports.template = function(strings, ...keys) {
  return (function(...values) {
    var dict = values[values.length - 1] || {};
    var result = [strings[0]];
    keys.forEach(function(key, i) {
      var value = Number.isInteger(key) ? values[key] : dict[key];
      result.push(value, strings[i + 1]);
    });
    return result.join('');
  });
}